<?php

namespace app\admin\model\litestore;

use addons\litestore\model\Litestoregoodsspec;
use app\admin\model\user\UserMoneyLog as MoneyLogModel;
use app\common\library\Ems as Emslib;
use think\Config;
use think\Db;
use think\Model;
use app\admin\model\User;

class Litestoreorder extends Model
{
    // 表名
    protected $name = 'litestore_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'pay_status_text',
        'pay_time_text',
        'freight_status_text',
        'freight_time_text',
        'receipt_status_text',
        'receipt_time_text',
        'order_status_text'
    ];
    

    
    public function getPayStatusList()
    {
        return ['10' => __('Unpaid'),'20' => __('Paid')];
    }     

    public function getFreightStatusList()
    {
        return ['10' => __('To be shipped'),'20' => __('Shipped')];
    }     

    public function getReceiptStatusList()
    {
        return ['10' => __('Goods not received'),'20' => __('Goods received')];
    }     

    public function getOrderStatusList()
    {
        return ['10' => __('In progress'),'20' => __('Cancel'),'30' => __('Completed')];
    }     


    public function getPayStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFreightStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['freight_status']) ? $data['freight_status'] : '');
        $list = $this->getFreightStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFreightTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freight_time']) ? $data['freight_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReceiptStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['receipt_status']) ? $data['receipt_status'] : '');
        $list = $this->getReceiptStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getReceiptTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['receipt_time']) ? $data['receipt_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPayTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setFreightTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setReceiptTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function address()
    {
        return $this->hasOne('Litestoreorderaddressen', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods()
    {
        return $this->hasMany('Litestoreordergoods','order_id','id');
    }
    public function user()
    {
        return $this->belongsTo('app\admin\model\User');
    }

    public function finish($order_id){
        if (!$order = self::get([
            'order_id' => $order_id,
            'order_status' => ['<>', '20']
        ],['goods','address'])) {
            throw new \Exception('订单不存在');
        }
        if ($order['freight_status'] === '10' || $order['receipt_status'] === '20') {
            $this->error = '该订单不合法';
            return false;
        }
        //订单返佣
        $this->add_return_money_bugoods($order->toArray());

        $config = Config::get('site');
        if($config['confirm_receipt_notification'] == 1){
            //邮件通知
            $email = $order['address']['email_address'];
            $msg = 'Your order: '.$order['order_no'].', confirmed receipt！';
            $ret = Emslib::notice($email, $msg);
        }

        return $order->save([
            'receipt_status' => '20',
            'receipt_time' => time(),
            'order_status' => '30'
        ]);
    }

    public function cancel($order_id){
        if ($this['pay_status'] === '20') {
            $this->error = '已付款订单不可取消';
            return false;
        }
        $goods = $this['goods'];
        $this->backGoodsStock($goods);

        $order = self::get([
            'order_id' => $order_id,
            'order_status' => ['<>', '20']
        ],['address']);

        //邮件通知
        $email = $order['address']['email_address'];
        $msg = 'Your order: '.$order['order_no'].', admin cancelled！';
        $ret = Emslib::notice($email, $msg);

        return $order->save([
            'order_status' => '20'
        ]);
    }
    private function backGoodsStock(&$goodsList)
    {
        $goodsSpecSave = [];
        foreach ($goodsList as $goods) {
            // 下单减库存
            if ($goods['deduct_stock_type'] === '10') {
                $goodsSpecSave[] = [
                    'goods_spec_id' => $goods['goods_spec_id'],
                    'stock_num' => ['inc', $goods['total_num']]
                ];
            }
        }
        if(!empty($goodsSpecSave)){
            // 更新商品规格库存
            return (new Litestoregoodsspec)->isUpdate()->saveAll($goodsSpecSave);
        }
        return true;
    }

    public function getOrderDetail($order_id){
        if (!$order = self::get([
            'order_id' => $order_id,
            'order_status' => ['<>', '20']
        ], ['goods'=>['spec','goods'], 'address'])) {
            throw new Exception('订单不存在');
        }
        $goodsList = [];
        foreach ($order['goods'] as $index => $item) {
            $item['image'] = cdnurl(explode(",",$item['images'])[0], true);
            $item['sku_image'] = $item['spec']['spec_image']=='' ? '' : cdnurl($item['spec']['spec_image'], true);
            $goodsList[] = $item;
        }
        $order['goods'] = $goodsList;
        return $order;
    }

    /**
     * 订单返佣-根据商品
     */
    public function add_return_money_bugoods($order){
        if($order['parent_user_id']){
            $rate_money_all = 0;
            foreach ($order['goods'] as $k=>$v){
                $rate_money = $v['total_price'] * ($v['blogger_rate']/100);
                $rate_money_all += $rate_money;
            }
            $model = User::find($order['parent_user_id']);
            if($model->group_id == 2){
                $before = $model->money;
                $model->money =  $before + $rate_money_all;
                if($rate_money_all>0){
                    $model->save();
                    (new MoneyLogModel())->add_money_log($order['parent_user_id'],$rate_money_all,$before,$model->money,'Order rebate, order no.:'.$order['order_no']);
                    Db::name('litestore_order')->where('id',$order['id'])->update(['rebates'=>$rate_money_all]);
                }
            }
        }
    }

}
